package com.qfedu.zf.index.service.impl;

import cn.hutool.core.convert.NumberWithFormat;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qfedu.zf.common.config.SystemConfig;
import com.qfedu.zf.common.utils.JwtUtil;
import com.qfedu.zf.common.vo.R;
import com.qfedu.zf.index.entity.Report;
import com.qfedu.zf.index.mapper.ReportMapper;
import com.qfedu.zf.index.service.ReportService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wgz
 * @since 2024-06-20
 */
@Service
public class ReportServiceImpl extends ServiceImpl<ReportMapper, Report> implements ReportService {

    @Autowired
    ReportMapper reportMapper;

    @Override
    public R add(String info, Integer userId, HttpServletRequest request) {
        String header = request.getHeader(SystemConfig.HEADER_TOKEN);
        if (header == null || header.equals("")) {
            return R.fail("请先登录");
        }
        int id = ((NumberWithFormat) JwtUtil.parseToken(header, "id")).intValue();
        if (id == userId) {
            return R.fail("不能举报自己");
        }
        Report report = new Report();
        report.setInfo(info);
        report.setUserId(userId);
        report.setReportDate(new Date());
        report.setBereportDate(new Date());
        report.setState(3);
        QueryWrapper<Report> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        List<Report> reports = reportMapper.selectList(queryWrapper);

        int update = 0;
        int insert;
        if (reports.size() > 0) {
            report.setCount(reports.size() + 1);
            for (Report report1 : reports) {
                report1.setCount(reports.size() + 1);
                update = reportMapper.updateById(report1);
            }
            insert = reportMapper.insert(report);
            if (insert > 0 && update > 0){
                return R.ok();
            }
        } else {
            report.setCount(1);
            insert = reportMapper.insert(report);
            if (insert > 0){
                return R.ok();
            }
        }
        return R.fail("举报失败");
    }
}
